﻿/*
    @公用代码封装 
    @author jason
    2015年9月9日17:15:23
*/

var normalParam = {};
var CJ = {
    url: "/api/commonapi",
    config: {
        beforeSend: null,
        complate: null,
        show_loading:true
    },
    ajaxGetJson: function (url, data, success) {
        CJ.ajaxGet(url, 'json', data, success);
    },
    ajaxGetXml: function (url, data, success) {
        CJ.ajaxGet(url, 'xml', data, success);
    },
    ajaxGetText: function (url, data, success) {
        CJ.ajaxGet(url, 'text', data, success);
    },
    ajaxGet: function (url, dataType, data, success) {
        CJ.baseAjax(url, 'get', dataType, data, success, null, null);
    },

    ajaxPostJson: function (url, data, success) {
        CJ.ajaxPost(url, 'json', data, success);
    },
    ajaxPost: function (url, dataType, data, success) {
        //var a = $.extend({}, normalParam, success);
        CJ.baseAjax(url, 'post', dataType, data, success, null, null);
    },
    ajaxPutJson: function (url, data, success) {
        CJ.ajaxPut(url, 'json', data, success);
    },
    ajaxPut: function (url, dataType, data, success) {
        CJ.baseAjax(url, 'put', dataType, data, success, null, null);
    },
    baseAjax: function (url, type, dataType, data, success, complate, error) {
        var index = 0;
        $.ajax({
            url: url,
            type: type,
            dataType: dataType,
            data: data,
            cache: false,
            beforeSend: function () {
                if (CJ.config.show_loading) {
                    index = layer.load(2, {
                        shade: [0.1, '#fff'] //0.1透明度的白色背景
                    });
                }
                if (typeof CJ.beforeSend === 'function') {
                    CJ.beforeSend.call(this);
                }
            },
            success: function (xhr) {
                layer.close(index);
                if (typeof success === 'function') {
                    success.call(xhr, xhr);
                }
            },
            complate: function (xhr) {
                layer.close(index);
                if (typeof CJ.complate === 'function') {
                    CJ.complate.call(this, xhr);
                }
            },
            error: function (x, y, z) {
                layer.close(index);
                console.log(x);
                console.log(y);
                console.log(z);
            }
        });
    },
    BindListPage: function (settings) {
        //normalSettings
        var ns = {
            url: "/api/commonapi", // api 请求路径
            tplId: "tpl",          //模板id
            containerId: "#dt_list", // 容器id
            data: undefined,
            pagerId: "#pager",
            page: 1,
            pageSize: 20,
            callBack: undefined
        };

        ns = $.extend({}, ns, settings);
        CJ.ajaxGetJson(ns.url, ns.data, function (xhr) {
            if (xhr && xhr.Success && xhr.Count > 0) {
                $(ns.containerId).empty().append(template(ns.tplId, xhr));
                var totalPage = xhr.ApiParamObj[1][0].totalPage;
                if (typeof ns.callBack === 'function') {
                    ns.callBack.call(this, xhr);
                }
                //渲染分页组件
                $(ns.pagerId).createPage({
                    pageCount: totalPage,
                    current: ns.data.page,
                    backFn: function (p) {
                        //单击回调方法，p是当前页码
                        ns.data.page = p;
                        CJ.BindListPage(ns, ns.data);
                        //阻止事件
                        return false;
                    }
                });
            }
        });
    },

    BindListPageSimple: function (settings) {
        //normalSettings
        var ns = {
            url: "/api/commonapi", // api 请求路径
            tplId: "tpl",          //模板id
            containerId: "#dt_list", // 容器id
            data: undefined,
            pagerId: "#pager",
            page: 1,
            pageSize: 20,
            callBack: undefined
        };

        ns = $.extend({}, ns, settings);


        CJ.ajaxGetJson(ns.url, ns.data, function (xhr) {
            if (xhr && xhr.Success && xhr.Count > 0) {
                $(ns.containerId).empty().append(template(ns.tplId, xhr));
                var totalPage = xhr.ApiParamObj[1][0].totalPage;
                if (typeof ns.callBack === 'function') {
                    ns.callBack.call(this, xhr);
                }
                $(ns.pagerId).click(function () {
                    if (ns.data.page < totalPage)
                        CJ.BindAfter(ns);
                });
            }
        });
    },
    BindAfter: function (ns) {
        ns.data.page += 1;
        CJ.ajaxGetJson(ns.url, ns.data, function (xhr) {
            if (xhr && xhr.Success && xhr.Count > 0) {
                $(ns.containerId).append(template(ns.tplId, xhr));
                if (typeof ns.callBack === 'function') {
                    ns.callBack.call(this, xhr);
                }
            }
        });
    },
    BindList: function (settings) {
        //normalSettings
        var ns = {
            url: "/api/commonapi", // api 请求路径
            tplId: "tpl",          //模板id
            containerId: "#dt_list", // 容器id
            data: undefined,
            pagerId: "#pager",
            page: 1,
            pageSize: 20,
            callBack: undefined
        };

        ns = $.extend({}, ns, settings);

        CJ.ajaxGetJson(ns.url, ns.data, function (xhr) {
            if (xhr && xhr.Success && xhr.Count > 0) {
                $(ns.containerId).empty().append(template(ns.tplId, xhr));
                if (typeof ns.callBack === 'function') {
                    ns.callBack.call(this, xhr);
                }
            } else {
                $(ns.containerId).empty();
            }
        });
    }
};

var zeropad = function (num) {
    return ((num < 10) ? '0' : '') + num;
};
var fmtdate = function (str) {
    str = str.replace(/-/g, "/");
    var date = new Date(str);
    return date;
}
/**
 * 时间格式化
 * @author Jason.Yang 
 * 2015年9月10日17:28:43
 * {{value.CreateTime | dateFormatTimeAgo}}>> 5分钟以前
 */
template.helper('dateFormatTimeAgo', function (dateStr) {
    var date = new Date(dateStr);
    if (date === NaN) return '';
    var isoDate = date.getUTCFullYear()
        + "-" + zeropad(date.getUTCMonth() + 1)
        + "-" + zeropad(date.getUTCDate())
        + "T" + zeropad(date.getUTCHours())
        + ":" + zeropad(date.getUTCMinutes())
        + ":" + zeropad(date.getUTCSeconds()) + "Z";
    return jQuery.timeago(isoDate);
});
/**
  * 时间格式化
  * @author Jason.Yang 
  * 2015年9月10日17:25:55
  *{{value.CreateTime | dateFormat:'yyyy年MM月dd日 HH时mm分'}}>> 2015年9月10日17时27分
  */
template.helper('dateFormat', function (dateStr, format) {
    if (dateStr == null || dateStr == '')return '-';
    var date = new Date(dateStr);
    if (date == NaN) return '';
    return date.pattern(format);
});

/**
 * 隐藏手机号
 * @ author Jason.Yang  
 * 2015年9月10日17:24:18
 * 15688886688>>156****6688
**/
template.helper('MobileHide', function (mobile) {
    if (mobile === null || mobile === undefined || mobile === "") return "";
    if (mobile.length < 8) return mobile;
    return mobile.substring(0, 3) + "*****" + mobile.substring(8, mobile.length);
});

/**
  * 订单状态 !TODO不是公用的
  * @author Jason.Yang 
  * 2015年12月17日15:34:18
  *
  */
template.helper('OrderStatusFormat', function (orderStatus) {
    return OrderStatusFormat(orderStatus);
});

function OrderStatusFormat(str) {
    if (str == "01_WAIT_RECEIVE")
        return "未接单";
    if (str == "02_RECEIVED")
        return "已接单等待查收";
    if (str == "03_CLIENT_READ")
        return "已查收等待派送";
    if (str == "04_DISPATCHING")
        return "派送中";
    if (str == "05_REFUSED_DISPATCH")
        return "已退单";
    if (str == "06_FINISH")
        return "配送完成";

    return "无状态";
}

/**       
 * 对Date的扩展，将 Date 转化为指定格式的String       
 * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符       
 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)       
 * eg:       
 * (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423       
 * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04       
 * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04       
 * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04       
 * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18       
 */
Date.prototype.pattern = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份           
        "d+": this.getDate(), //日           
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时           
        "H+": this.getHours(), //小时           
        "m+": this.getMinutes(), //分           
        "s+": this.getSeconds(), //秒           
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度           
        "S": this.getMilliseconds() //毫秒           
    };
    var week = {
        "0": "\u65e5",
        "1": "\u4e00",
        "2": "\u4e8c",
        "3": "\u4e09",
        "4": "\u56db",
        "5": "\u4e94",
        "6": "\u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
/**
 * @QueryStringByName 获取url中 key对应的值
 * @author: yangxing1002@gmail.com
 **/
function getQueryStringByName(name) {
    var result = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
    if (result == null || result.length < 1) {
        return "";
    }
    return result[1];
}

//用于MVC参数适配JavaScript闭包函数

var mvcParamMatch = (function () {
    var MvcParameterAdaptive = {};
    //验证是否为数组
    MvcParameterAdaptive.isArray = Function.isArray || function (o) {
        return typeof o === "object" &&
                Object.prototype.toString.call(o) === "[object Array]";
    };

    //将数组转换为对象
    MvcParameterAdaptive.convertArrayToObject = function (/*数组名*/arrName, /*待转换的数组*/array, /*转换后存放的对象，不用输入*/saveOjb) {
        var obj = saveOjb || {};

        function func(name, arr) {
            for (var i in arr) {
                if (!MvcParameterAdaptive.isArray(arr[i]) && typeof arr[i] === "object") {
                    for (var j in arr[i]) {
                        if (MvcParameterAdaptive.isArray(arr[i][j])) {
                            func(name + "[" + i + "]." + j, arr[i][j]);
                        } else if (typeof arr[i][j] === "object") {
                            MvcParameterAdaptive.convertObject(name + "[" + i + "]." + j + ".", arr[i][j], obj);
                        } else {
                            obj[name + "[" + i + "]." + j] = arr[i][j];
                        }
                    }
                } else {
                    obj[name + "[" + i + "]"] = arr[i];
                }
            }
        }

        func(arrName, array);

        return obj;
    };

    //转换对象
    MvcParameterAdaptive.convertObject = function (/*对象名*/objName,/*待转换的对象*/turnObj, /*转换后存放的对象，不用输入*/saveOjb) {
        var obj = saveOjb || {};

        function func(name, tobj) {
            for (var i in tobj) {
                if (MvcParameterAdaptive.isArray(tobj[i])) {
                    MvcParameterAdaptive.convertArrayToObject(i, tobj[i], obj);
                } else if (typeof tobj[i] === "object") {
                    func(name + i + ".", tobj[i]);
                } else {
                    obj[name + i] = tobj[i];
                }
            }
        }

        func(objName, turnObj);
        return obj;
    };

    return function (json, arrName) {
        arrName = arrName || "";
        if (typeof json !== "object") throw new Error("请传入json对象");
        if (MvcParameterAdaptive.isArray(json) && !arrName) throw new Error("请指定数组名，对应Action中数组参数名称！");

        if (MvcParameterAdaptive.isArray(json)) {
            return MvcParameterAdaptive.convertArrayToObject(arrName, json);
        }
        return MvcParameterAdaptive.convertObject("", json);
    };
})();

function newcall(phone) {
    layer.open({
        type: 2,
        area: ['80%', '90%'],
        fix: false, //不固定
        closeBtn: 1,
        maxmin: true,
        content: '/HTMLS/Orders/neworder.html?phone=' + phone + '&r' + $.now()
});
}